using Microsoft.VisualBasic.Devices;
using MiniFox.Infrastructure;
using MiniFox.Net;
using MiniFox.Net.Http;
using System;
using System.ComponentModel;
using WinForWebApi.Models;

namespace WinForWebApi
{
    public partial class frmMain : Form
    {
        readonly HttpAdapter httpAdapter;
        public frmMain()
        {
            InitializeComponent();
            var container = WebAdapterFactory.Container;
            this.httpAdapter = container.GetHttpAdapterByName("device");
            this.dgDeviceData.AutoGenerateColumns = false;
            this.dgDeviceData.InitDataGridColumns<DeviceVo>();
        }

        private async Task QueryAsync()
        {
            var requestObj = new PagedQueryObject
            {
                SortField = "CreateTime",
                SortDesc = true,
                PageIndex = 1,
                PageSize = 50,
                Parameters = new
                {
                    Keyword = ""
                }
            };

            var service = this.httpAdapter.GetService("query");
            var task = service.PostAsync<PagedQueryObject, Response<PagedResultObject<List<DeviceVo>>>>(requestObj);

            var response = await task;
            this.dgDeviceData.DataSource = new BindingList<DeviceVo>(response.Data.Result);
            this.dgDeviceData.Refresh();
        }

        private async void frmMain_Load(object sender, EventArgs e)
        {
            await this.QueryAsync();
        }

        private async void btnInsert_Click(object sender, EventArgs e)
        {
            var editForm = new EditForm(null);
            var result = editForm.ShowDialog();
            if (result == DialogResult.OK)
            {
                await this.QueryAsync();
            }
        }

        private async void dgDeviceData_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            var row = this.dgDeviceData.Rows[e.RowIndex];
            var deviceVo = row.DataBoundItem as DeviceVo;
            var editForm = new EditForm(deviceVo.deviceId);
            var result = editForm.ShowDialog();
            if (result == DialogResult.OK)
            {
                await this.QueryAsync();
            }
        }

        private async void btnRemove_Click(object sender, EventArgs e)
        {
            bool success = true;
            foreach (DataGridViewRow row in this.dgDeviceData.SelectedRows)
            {
                var deviceVo = row.DataBoundItem as DeviceVo;

                var service = this.httpAdapter.GetService("delete");
                var task = service.PostAsync<string, Response<string>>(deviceVo.deviceId);
                var response = await task;
                success &= response.Success;
            }
            if (success)
                await this.QueryAsync();
        }

        private async void btnRefresh_Click(object sender, EventArgs e)
        {
            await this.QueryAsync();
        }
    }
}
